//
//  YFChooseTemplateVc.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/29.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFChooseTemplateVc.h"
#import "YFCustomTemplateCell.h"
#import "YFSystemTemplateCell.h"
#import "NSString+Extension.h"
#import "YFSectionHeadView.h"
#import "YFCreatTemplateVc.h"
#import <pop/POP.h>
#import "YFThreeDViewController.h"
#import "YFCustomPlaceholderView.h"
#import "YFSportAndSensorApi.h"

#define kSystemTemplateCellHeight kAutoHei(209)
#define kCustomTemplateCellHeight kAutoHei(115) + 7

@interface YFChooseTemplateVc ()<UITableViewDelegate,UITableViewDataSource,YFThreeDViewControllerDelegate>
// 自定义模板空白占位视图
@property (nonatomic, strong) YFCustomPlaceholderView *customPlaceholderView;
/** 系统模板头部视图 */
@property (nonatomic, strong) YFSectionHeadView *systemHeadview;
/** 自定义模板头部视图 */
@property (nonatomic, strong) YFSectionHeadView *customHeadView;

//@property (nonatomic, weak) UIButton *creatTemplateButton;
/** 编辑按钮 */
@property (nonatomic, strong) UIButton *editButton;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 自定义模板 */
@property (nonatomic, strong) NSMutableArray *customTemplateArr;

@property (nonatomic, assign)BOOL isEditing;


@end

@implementation YFChooseTemplateVc {
    User *_user;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _user = [User getLastUser];
    [self configuerUi];
}
- (void)configuerUi {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"Replacement Model";
    self.view.backgroundColor = kSeparationLineColor;
    self.tableView.backgroundColor = kSeparationLineColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    [self.creatTemplateButton clipsCornerRadius:3];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, 100)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Nav_addTemplate"] style:UIBarButtonItemStyleDone target:self action:@selector(creatTemplateBtnClick:)];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
//    [self CreatAddTemplateButton];
}

// 创建添加模板的按钮
/*
- (void)CreatAddTemplateButton {
    if (_creatTemplateButton == nil) {
        UIButton *creatButton = [UIButton creatButtonTitle:@"Creat your template" bgColor:kYellowGreenColor textFont:kOpenSansFont(OpenSansExtraBold, 16) textColor:kTBlackText];
        [creatButton clipsCornerRadius:3];
        CGFloat btnY = self.view.bounds.size.height - kAutoHei(46) - 25;
        creatButton.frame = CGRectMake((kYFScreenWidth - kAutoWid(267)) * 0.5, btnY,kAutoWid(267), kAutoHei(46));
        [self.view addSubview:creatButton];
        _creatTemplateButton = creatButton;
        [creatButton addTarget:self action:@selector(creatTemplateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
 */

- (void)creatTemplateBtnClick:(UIButton *)sender {
    self.isEditing = NO;
    YFThreeDViewController *threeDVc = [[YFThreeDViewController alloc] initWithNibName:@"YFThreeDViewController" bundle:nil];
    threeDVc.type = kThreeDRealTypeRecordTemplate;
    threeDVc.delegate = self;
    [self.navigationController pushViewController:threeDVc animated:YES];
//    YFCreatTemplateVc *creatVc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"YFCreatTemplateVc"];
//    creatVc.title = @"Create Model";
//    [self.navigationController pushViewController:creatVc animated:YES];
}
#pragma mark - YFThreeDViewControllerDelegate
- (void)didSaveRecordTemplateWithTemplateItem:(YFThreeDTemplate *)templateItem {
    [self.customTemplateArr removeAllObjects];
    self.customTemplateArr = nil;
    _user = [User getLastUser];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}

// deleteCurrentTemplate 是否删除当前模板
- (void)deleteSeletedCustomTemplateWithDeleteCurrentTemplate:(BOOL)deleteCurrentTemplate {
    
    __weak typeof(self)weakSelf = self;
    NSArray *deleteArr  = [self getAllNeedDeleteTemplatesShowAlert:YES deleteCurrentTemplate:deleteCurrentTemplate];
    // 删除操作
    if (deleteArr.count == 0) {
        return;
    }
    FUIAlertView *alert = [FUIAlertView alertWithTitle:@"Prompt" message:@"Are you sure you want to delete this action template? After deleted.can never be retrieved" cancelTitle:@"Reconsider" confirmTitle:@"Confirm"];
    [alert show];
    [alert setOnOkAction:^{
        
        [weakSelf.hud showWithMaskType:WSProgressHUDMaskTypeClear];
        NSMutableArray *templateIDs = [NSMutableArray array];
        for (YFThreeDTemplate *templateModel in deleteArr) {
            if (templateModel.templateID.length > 0) {
                NSString *templateID = [NSString stringWithFormat:@"%@",templateModel.templateID];
                [templateIDs addObject:templateID];
            }
        }
    
        [YFSportAndSensorApi deleteTemplateToServer:templateIDs.mutableCopy complete:^(NSError *error) {
            if (error) {
                [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud dismiss];
                    [[RLMRealm defaultRealm] beginWriteTransaction];
                    [[RLMRealm defaultRealm] deleteObjects:deleteArr];
                    [[RLMRealm defaultRealm] commitWriteTransaction];
                    [weakSelf.customTemplateArr removeAllObjects];
                    weakSelf.customTemplateArr = nil;
                    weakSelf.isEditing = NO;
                    _user = [User getLastUser];
                    if (deleteCurrentTemplate && _user.currentSelectTemplate == nil) {
                        [[RLMRealm defaultRealm] beginWriteTransaction];
                        _user.currentSelectTemplate = [YFThreeDTemplate getCurrentUserAllSystemTemplateModels].firstObject;
                        [[RLMRealm defaultRealm] commitWriteTransaction];
                    }
                    [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
                });
            }
        }];
    }];
    [alert setOnCancelAction:^{
        self.isEditing = NO;
    }];
}

// 找出所有被标记为删除的模板
- (NSArray <YFThreeDTemplate *>*)getAllNeedDeleteTemplatesShowAlert:(BOOL)showTip deleteCurrentTemplate:(BOOL)deleteCurrentTemplate {
    if (_isEditing) {
        NSArray *resluts = [self.customTemplateArr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isDeletSelect == YES"]];
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:resluts];
        for (YFThreeDTemplate *model in arrM) {
            if ([model.identification isEqualToString:_user.currentSelectTemplate.identification]) {
                if (deleteCurrentTemplate) {
                   
                }else {
                    if (showTip && arrM.count == 1) {
                        [self.hud showErrorWithString:NSLocalizedString(@"Cannot delete the current template", @"当前模板不能删除") dimissAfterSecond:1.5];
                    }
                    [arrM removeObject:model];
                }
                break;
            }
        }
        return arrM.copy;
    }
    return nil;
}

#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return self.customTemplateArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YFSystemTemplateCell class]) forIndexPath:indexPath];
        YFSystemTemplateCell *systemCell = (YFSystemTemplateCell *)cell;
        __weak typeof(self) weakSelf = self;
        [systemCell setDidSelectSystemTemplateBlock:^(NSInteger index, YFThreeDTemplate *selectTemplate) {
           // NSIndexPath *oldIndexPath = [weakSelf getOldUserSelectTemplateIndexPath];
            if (weakSelf.isEditing == NO) {
                [[RLMRealm defaultRealm] beginWriteTransaction];           _user.currentSelectTemplate = selectTemplate;
                [[RLMRealm defaultRealm] commitWriteTransaction];
                [weakSelf.hud showSuccessWithString:@"Select Action Model Success"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf.hud setHidden:YES];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
            }
        }];
    }else {
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([YFCustomTemplateCell class]) forIndexPath:indexPath];
        YFCustomTemplateCell *customCell = (YFCustomTemplateCell *)cell;
        [customCell configuerCellWithModel:[self.customTemplateArr objectAtIndex:indexPath.row] isEditing:_isEditing];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
   
    
    if (indexPath.section == 1) {
         // 获取点击的Cell
        YFCustomTemplateCell *customCell = [tableView cellForRowAtIndexPath:indexPath];
        
        YFThreeDTemplate *threeDtemplate = [self.customTemplateArr objectAtIndex:indexPath.row];
        if (_isEditing) {
            threeDtemplate.isDeletSelect = !threeDtemplate.isDeletSelect;
            [customCell configuerCellWithModel:threeDtemplate isEditing:_isEditing];
            // 检测是否有选中要删除的
            [self checkHaveSelectDelectTemplate];
        }else {
            // 获取当前用户已选模板的索引
            NSIndexPath *oldIndexPath = [self getOldUserSelectTemplateIndexPath];
            YFThreeDTemplate *template = [self.customTemplateArr objectAtIndex:indexPath.row];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            _user.currentSelectTemplate = template;
            [[RLMRealm defaultRealm] commitWriteTransaction];
            if (oldIndexPath != nil && oldIndexPath.section == 1) {
                [tableView reloadRowsAtIndexPaths:@[indexPath,oldIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            }else {
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
            [self.hud showSuccessWithString:@"Select Template Success"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.hud setHidden:YES];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }
}

// 获取原来选择的模板对应的索引:作用：刷新cell
- (NSIndexPath *)getOldUserSelectTemplateIndexPath {
    if (_user.currentSelectTemplate != nil) {
        if( _user.currentSelectTemplate.mainType == TemplateMainTypeMy){
            for (NSInteger i = 0; i < self.customTemplateArr.count; i++) {
                YFThreeDTemplate *model = self.customTemplateArr[i];
                if ([model.identification isEqualToString:_user.currentSelectTemplate.identification]) {
                   return [NSIndexPath indexPathForRow:i inSection:1];
                }
            }
        }else if (_user.currentSelectTemplate.mainType == TemplateMainTypeSystem) {
            RLMResults *result = [[YFThreeDTemplate getCurrentUserAllSystemTemplateModels] objectsWithPredicate:[NSPredicate predicateWithFormat:@"identification == %@",_user.currentSelectTemplate.identification]];
            NSInteger index = [self.customTemplateArr indexOfObject:result.firstObject];
            return [NSIndexPath indexPathForRow:index inSection:0];
        }
    }
    return nil;
}

- (BOOL)checkHaveSelectDelectTemplate {
    BOOL have = NO;
    for (YFThreeDTemplate *item in self.customTemplateArr) {
        if (item.isDeletSelect == YES) {
            have = YES;
            break;
        }
    }
    [self.editButton setTitle:have ? @"Delete":@"Cancel" forState:UIControlStateSelected];
    if (have) {
        [self.editButton setTitleColor:kTRedEEText forState:UIControlStateSelected];
    }else {
        [self.editButton setTitleColor:kTWhiteText forState:UIControlStateSelected];
    }
//
//    [self.creatTemplateButton setTitleColor:(have ? kTWhiteText:kTLightGray999) forState:UIControlStateNormal];
//    self.creatTemplateButton.enabled = have;
    return have;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return kSystemTemplateCellHeight;
    }else {
        return kCustomTemplateCellHeight;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return self.systemHeadview;
    }else {
        YFSectionHeadView *sectionView = [self customHeadView];
        self.editButton.hidden = self.customTemplateArr.count == 0;
        return sectionView;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kAutoHei(55);
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1 && self.customTemplateArr.count == 0){
        return self.customPlaceholderView;
    }
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1 && self.customTemplateArr.count == 0){
        return  self.customPlaceholderView.bounds.size.height;
    }
    return 0.000001;
}

#pragma mark - scorllview代理方法
/*
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.customTemplateArr.count > 3) {
        [UIView animateWithDuration:0.3 animations:^{
            self.creatTemplateButton.alpha = 0;
        } completion:^(BOOL finished) {
            self.creatTemplateButton.hidden = YES;
        }];
    }else {
        self.creatTemplateButton.hidden = NO;
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.customTemplateArr.count > 3) {
        [UIView animateWithDuration:0.3 animations:^{
            self.creatTemplateButton.alpha = 1;
        } completion:^(BOOL finished) {
            self.creatTemplateButton.hidden = NO;
        }];
    }else {
        self.creatTemplateButton.alpha = 1;
        self.creatTemplateButton.hidden = NO;
    }
}
 */
#pragma mark -  getter & setter
- (NSMutableArray *)customTemplateArr {
    if (_customTemplateArr == nil) {
        RLMResults *results = [YFThreeDTemplate getCurrentUserAllCustomTemplateModels];
        NSMutableArray *arrM = [NSMutableArray array];
        for (YFThreeDTemplate *model in results) {
            [arrM addObject:model];
        }
        _customTemplateArr = arrM;
    }
    return _customTemplateArr;
}

#pragma mark - Tableview的头啊尾啊
- (YFSectionHeadView *)systemHeadview {
    if (!_systemHeadview) {
        _systemHeadview = [YFSectionHeadView sectionHeadView];
        [_systemHeadview sectionHeadViewWithTitle:@"Demo Action Model" buttonTitle:nil showRightBtn:NO];
    }
    
    return _systemHeadview;
}

- (YFSectionHeadView *)customHeadView {
    if (!_customHeadView) {
        _customHeadView = [YFSectionHeadView sectionHeadView];
        [_customHeadView sectionHeadViewWithTitle:@"My Action Model" buttonTitle:@"Edit" showRightBtn:YES];
        [_customHeadView.rightBtn setTitleColor:kTWhiteText forState:UIControlStateNormal];
        [_customHeadView.rightBtn setTitle:@"Cancel" forState:UIControlStateSelected];
        _editButton = _customHeadView.rightBtn;
        __weak typeof(self) weakSelf = self;
        [_customHeadView setRightButtonAction:^(UIButton *sendr) {
            if (weakSelf.isEditing == NO) {
                weakSelf.isEditing = YES;
            }else {
                if ([weakSelf checkHaveSelectDelectTemplate]) {
                    // 删除操作
                    [weakSelf deleteSeletedCustomTemplateWithDeleteCurrentTemplate:YES];
                }else {
                    weakSelf.isEditing = NO;
                }
            }
        }];
    }
    return _customHeadView;
}

- (void)setIsEditing:(BOOL)isEditing {
    _isEditing = isEditing;
    self.editButton.selected = isEditing;
//    [self switchCreatTemplateButtonState:!isEditing];
    if (self.isEditing == NO) {
        [self.customTemplateArr makeObjectsPerformSelector:@selector(setIsDeletSelect:) withObject:@(NO)];
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
}

- (YFCustomPlaceholderView *)customPlaceholderView {
    if (_customPlaceholderView == nil) {
        YFCustomPlaceholderView *placeHolderView = [YFCustomPlaceholderView customPlaceholderView];
        _customPlaceholderView = placeHolderView;
    }
    return _customPlaceholderView;
}

#pragma makr - 动画
// 添加模板和删除模板状态切换
/*
- (void)switchCreatTemplateButtonState:(BOOL)showAdd {
    CGRect toFrame;
    if (showAdd) {
        CGFloat btnY = self.view.bounds.size.height - kAutoHei(46) - 25;
        toFrame = CGRectMake((kYFScreenWidth - kAutoWid(267)) * 0.5, btnY,kAutoWid(267), kAutoHei(46));
        [self.creatTemplateButton clipsCornerRadius:3];
        self.creatTemplateButton.enabled = YES;
        [self.creatTemplateButton setTitle:@"Create your template" forState:UIControlStateNormal];
    }else {
        CGFloat btnY = self.view.bounds.size.height - 64;
        toFrame = CGRectMake(0, btnY,kYFScreenWidth, 64);
        [self.creatTemplateButton clipsCornerRadius:0];
        [self checkHaveSelectDelectTemplate];
        [self.creatTemplateButton setTitle:@"Delete" forState:UIControlStateNormal];
    }
    [self.creatTemplateButton setTitleColor:showAdd ?kTBlackText:kTLightGray666 forState:UIControlStateNormal];
    self.creatTemplateButton.backgroundColor = kYellowGreenColor;
    POPSpringAnimation *springA = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    springA.fromValue = [NSValue valueWithCGRect:self.creatTemplateButton.frame];
    springA.toValue = [NSValue valueWithCGRect:toFrame];
    springA.springSpeed = 5;
    springA.springBounciness = 1;
    springA.beginTime = CACurrentMediaTime();
    [self.creatTemplateButton pop_addAnimation:springA forKey:nil];
}
 */

@end


